/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.common.security.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.core.constants.ServiceConstants;
import cn.zmwh.common.core.utils.I18nUtils;
import cn.zmwh.common.security.base.LoginService;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.config.JwtTokenUtil;
import cn.zmwh.common.security.pojo.dto.LoginDTO;
import cn.zmwh.common.security.pojo.request.LoginRequest;
import cn.zmwh.common.security.pojo.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @describe: 验证码登录 、
 * @author: dmzmwh 、
 * @time: 2025-03-11 16:41 、
 */
@Slf4j
@Service(value = "password" + ServiceConstants.LOGIN)
public class LoginServicePassword implements LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public LoginVo login(LoginRequest request) {
        LoginVo loginVo = new LoginVo();
        String code = request.getCode();
        if (StrUtil.isBlank(code)) {
            loginVo.setMsg("验证码不能为空");
            return loginVo;
        }
        LoginDTO loginDTO = new LoginDTO();
        BeanUtil.copyProperties(request, loginDTO);
        UserDetails userDetails = userService.loadUser(loginDTO);
        if (!passwordEncoder.matches(request.getPassword(), userDetails.getPassword())) {
            loginVo.setMsg(I18nUtils.getWithDefault("user.password.error", "密码错误"));
            loginVo.setSuccess(0);
            return loginVo;
        }
        String token = jwtTokenUtil.generateToken(userDetails, request.getTerminal());
        loginVo.setToken(token);
        loginVo.setSuccess(1);
        return loginVo;
    }
}
